package com.example.handler;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.example.dto.BusinessUserDTO;
import com.example.dto.SysUserDTO;
import com.example.feign.UsernameFeignClient;
import com.example.model.api.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class ThirdOauth2AuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Value("${defaultClientId}")
    private String defaultClientId;

    @Value("${defaultClientSecret}")
    private String defaultClientSecret;

    @Value("${defaultClientPrimaryId}")
    private Long defaultClientPrimaryId;

    @Value("${defaultStoreId}")
    private Long defaultStoreId;

    @Value("${defaultTenantId}")
    private Long defaultTenantId;


    @Autowired
    public Environment environment;

    @Autowired
    public UsernameFeignClient usernameFeignClient;

    @Autowired
    private JdbcOperations jdbcTemplate;

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        Object principal = authentication.getPrincipal();
        if (principal instanceof OAuth2User) {
            OAuth2User oauth2User = (OAuth2User) principal;
            Map<String, Object> attributes = oauth2User.getAttributes();
            String username = (String) attributes.get("name");
            // 判断用户是否存在
            Result<SysUserDTO> sysUsername = usernameFeignClient.getSysUsername(username);
            SysUserDTO data = sysUsername.getData();
            // 用户存在
            if (data == null) {
                // 用户不存在，新建
                String avatar_url = (String) attributes.get("avatar_url");
                String email = (String) attributes.get("email");
                SysUserDTO sysUserDTO = new SysUserDTO();
                sysUserDTO.setUsername(username);
                sysUserDTO.setEmail(email);
                sysUserDTO.setDeptId(0L);
                sysUserDTO.setHeadUrl(avatar_url);
                usernameFeignClient.saveThirdOauth2(sysUserDTO);
            }

            JdbcRegisteredClientRepository registeredClientRepository = new JdbcRegisteredClientRepository(jdbcTemplate);
            RegisteredClient client = registeredClientRepository.findByClientId(defaultClientId);
            String redirectUri = ListUtil.toList(client.getRedirectUris()).get(0);
            String authUrl = StrUtil.format("{}/oauth2/authorize?client_id={}&redirect_uri={}&response_type=code&scope=message.read", environment.getProperty("spring.security.oauth2.resourceserver.jwt.issuer-uri"), defaultClientId,  redirectUri);
            response.sendRedirect(authUrl);
        }
    }
}